# -*- coding:utf-8 -*-

import os
import sys
import shutil
import time
import thread
import threading
import zipfile
import glob
import signal
from hashlib import md5

from MyException import Error
from MyException import GetSizeError
from MyException import NotFileError
from MyException import BigFileError
from MyException import BigZipError
from MyException import NonZipError
from MyException import CopyFileError
from MyLogger import MyLogger, SIZEROTATE, TIMEROTATE
from StatLog import StatLog
from ConfigInfo import Profile
import GlobalVar as GlobalVar

class MyCacheMonitor(threading.Thread):
    def __init__(self, profile):
        threading.Thread.__init__(self)
        self.profile = profile

        self.run_logger = MyLogger(os.path.join(profile.log_dir, "Cache_Dir_monitor.log"), SIZEROTATE, profile.size_rotate_backup_num)
        self.run_logger.set_log_lev(profile.log_lev)

    def run(self):
        while GlobalVar.get_run_flag():
            time.sleep(1)

            # 获取目录下的zip文件列表
            zip_files = glob.glob('%s/*.zip' % (self.profile.cache_dir))
            if len(zip_files) == 0 :
                self.run_logger.debug("[Cache Monitor Thread] Cache dir clean")
                continue

            # 判断时间，是否在解压线程工作时间内
            start_time_str = time.strftime("%Y%m%d ", time.localtime()) + self.profile.unzip_bigdata_start
            end_time_str = time.strftime("%Y%m%d ", time.localtime()) + self.profile.unzip_bigdata_end
            self.run_logger.debug("[Cache Monitor Thread] Unzip %s thread working hours from %s to %s" % (
            "Bigdata", start_time_str, end_time_str))

            if self.compare_time(start_time_str, end_time_str):
                self.move_zipfiles_to_dir(zip_files, self.profile.recv_zip)
            else:
                continue

        self.run_logger.info("[Cache Monitor Thread] exit")

    def compare_time(self, start_time_str, end_time_str):
        """
        比较当前时间与start_time_str, 和end_time_str，如果在它们中间返回True，否则返回False
        :param start_time_str: 开始时间，格式为"yyyyMMdd HH:MM"
        :param end_time_str: 结束时间，格式同上
        :return: 
        """
        s_time = None
        c_time = None
        e_time = None
        try:
            s_time = time.mktime(time.strptime(start_time_str,'%Y%m%d %H:%M'))
            e_time = time.mktime(time.strptime(end_time_str,'%Y%m%d %H:%M'))
            c_time = time.time()
        except Exception, e:
            self.run_logger.error("[Cache Monitor Thread] fail to mktime")
            self.run_logger.error("[Cache Monitor Thread] %s"%( repr(e)))
            #os.kill(os.getpid(), signal.SIGKILL)

        self.run_logger.debug("[Cache Monitor Thread] s_time ; %s" % (str(s_time)))
        self.run_logger.debug("[Cache Monitor Thread] e_time ; %s" % (str(e_time)))
        self.run_logger.debug("[Cache Monitor Thread] c_time ; %s" % (str(c_time)))

        if (float(c_time) > float(s_time)) and (float(c_time) < float(e_time)):
            return True
        else:
            return False

    def move_zipfiles_to_dir(self, zipfiles, dir):
        """
        移动zip文件到cache_dir，在时间控制逻辑里被调用
        :param zipfiles: 待移动的文件列表
        :return: 
        """
        for file in zipfiles:
            # 拼接文件名
            filename = os.path.split(file)[1]
            dst_file_path = os.path.join(dir, filename)
            tmp_file_path = dst_file_path + ".tmp"

            self.run_logger.debug("[Cache Monitor Thread] ready to move %s to %s"%(filename, dir))
            try:
                # move文件为tmp_file_path
                shutil.copyfile(file, tmp_file_path)
                # rename 临时文件tmp_file_path为dst_file_path
                os.rename(tmp_file_path, dst_file_path)
            except Exception, e:
                self.run_logger.error("[Cache Monitor Thread] move zip file to cache_dir failed")
                self.run_logger.error("[Cache Monitor Thread] %s"%(repr(e)))
            # 删除原文件
            os.remove(file)
